<?php
Yii::import('zii.widgets.jui.CJuiInputWidget');
class JAccountTokenCategorySelector extends CJuiInputWidget {
	public function init() {
		parent::init();
		$assetsUrl = Yii::app()->assetManager
			->publish(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets', false, -1, YII_DEBUG);
		$cs = Yii::app()->getClientScript();
		$cs->registerScriptFile($assetsUrl . '/jx.account.token.category.js');
	}

	public function run() {
		list($name, $id) = $this->resolveNameID();
		if (isset($this->htmlOptions['id']))
			$id = $this->htmlOptions['id'];
		else
			$this->htmlOptions['id'] = $id;

		$categoryId = $this->value;

		if ($this->hasModel()) {
			$attribute=$this->attribute;
			CHtml::resolveName($this->model, $attribute);
			$categoryId = $this->model->{$attribute};
			echo CHtml::activeHiddenField($this->model, $this->attribute, $this->htmlOptions);
		} else {
			echo CHtml::hiddenField($name, $this->value, $this->htmlOptions);
		}

		$Unselectedlabel = $label = '未选择科目';
		if ($categoryId) {
			$category = AccountTokenCategory::model()->findByPk($categoryId);
			if ($category) {
				$label = $category->getDisplayLongName();
			}
		}

		$label = CJSON::encode($label);
		$categorySearchUrl = CJSON::encode(
			Yii::app()->getController()->createUrl('accountTokenCategory/search'));
//		$materialSearchUrl = CJSON::encode(
//			Yii::app()->getController()->createUrl('material/search'));

//		$inputJs = $this->unitInputId ? "if(!jQuery('#{$this->unitInputId}').val()){jQuery('#{$this
//				->unitInputId}').val(model.unit);}" : '';
		$js = <<<EOF
Ext.onReady(function(){
JX.Account.Token.Category.categorySearchUrl=$categorySearchUrl;
	new Ext.Button({
		renderTo: '$id-container',
		text: $label,
		handler: function(button){
			JX.Account.Token.Category.chooseCategory(function(category){
				if(category){
					button.setText(category.displayLongName);
					jQuery('#$id').val(category.id);
					//$ inputJs
				}else{
					button.setText('$Unselectedlabel');
					jQuery('#$id').val('');
				}
			});
		}
	});
});				
				
EOF
		;

		$cs = Yii::app()->getClientScript();
		$cs->registerScript(__CLASS__ . '#' . $id, $js, CClientScript::POS_END);
		echo CHtml::tag('div', array(
			'id' => $id . '-container'
		), '');
	}
}
